package com.glsc.ngateway.flowable.listener.createproductnew;

import com.glsc.ngateway.common.api.flowable.dto.Result;
import com.glsc.ngateway.flowable.service.FlowableUserService;
import com.glsc.ngateway.flowable.service.feign.IEurekaAmproductFeignService;
import org.flowable.bpmn.model.UserTask;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

@Component
public class CreateProductNewKfqHandler implements ExecutionListener {

    private static final Logger logger = LoggerFactory.getLogger(CreateProductNewKfqHandler.class);

    public static CreateProductNewKfqHandler kfqHandler;
    @Autowired
    private FlowableUserService flowableUserService;
    @Autowired
    IEurekaAmproductFeignService amproductFeignService;

    @PostConstruct
    public void init() {
        kfqHandler = this;
        kfqHandler.flowableUserService = this.flowableUserService;
        kfqHandler.amproductFeignService = this.amproductFeignService;
    }


    @Override
    public void notify(DelegateExecution execution) {

        try {

            //delegateTask.setAssignee("老板");


//        String department = createProductStartHandler.flowableUserService.getDepartment(userid);
//        delegateTask.setVariable("teamleader", createProductStartHandler.flowableUserService.getLeader(userid));
//        delegateTask.setVariable("manager", createProductStartHandler.flowableUserService.getManager(department));
//
            if (true) {
                //TODO 符合一定条件自动complete
                execution.setVariable("_FLOWABLE_SKIP_EXPRESSION_ENABLED", true);
                UserTask userTask = (UserTask) execution.getCurrentFlowElement();
                userTask.setSkipExpression("${1==1}");
                execution.setVariable("qdManagerGroupSize", 0);
            } else {
                //渠道市场经理
                Result<List<String>> qdManagerGroup =
                        kfqHandler.amproductFeignService.findAmProductUserIdList("amprod.role.市场经理");
                if (qdManagerGroup.getCode() == 10000) {
                    execution.setVariable("qdManagerGroup", qdManagerGroup.getData());
                    execution.setVariable("qdManagerGroupSize", qdManagerGroup.getData().size());
                } else {
                    throw new Exception("查询amprod.role.市场经理。");
                }
            }

        } catch (Exception e) {
            logger.error("CreateProductNewKfqHandler处理异常，结束处理。processid=" + execution.getProcessInstanceId(), e);
            throw new RuntimeException("CreateProductNewKfqHandler处理异常，结束处理。processid=" + execution.getProcessInstanceId(), e);
        }
    }

}